package tom.oauth2.async;

import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurerSupport;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;

/**
 * <code>@EnableAsync启用异步支持，配置异步线程池支持@Async注解</code>
 * 实现{@link org.springframework.scheduling.annotation.AsyncConfigurer} 或者继承 {@link AsyncConfigurerSupport}
 * @author ZHUFEIFEI
 */
@Slf4j
@Configuration
@EnableAsync
public class AsyncExecutorConfiguration extends AsyncConfigurerSupport {

    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(5);
        executor.setMaxPoolSize(20);
        executor.setKeepAliveSeconds(60);
        executor.setQueueCapacity(30);
//        executor.setRejectedExecutionHandler();
        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.setThreadNamePrefix("Async_");
        //装饰器可以对任务前后做一些监控操作
//        executor.setTaskDecorator();
        //如果作为bean不需要调用，否则手动初始化
        executor.initialize();
        return executor;
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return (ex, method, params) -> {
                log.error("Async execute : {} param : {} exception !", method.getName(), params, ex);
        };
    }
}
